package com.sunseen.capacitormachine.modules.parameter.productparameter.edit;

import android.util.Log;
import android.view.View;
import android.widget.RadioGroup;
import android.widget.Toast;

import androidx.databinding.ViewDataBinding;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sunseen.capacitormachine.R;
import com.sunseen.capacitormachine.common.BaseFragment;
import com.sunseen.capacitormachine.commumication.http.HttpUtil;
import com.sunseen.capacitormachine.commumication.http.RestClient;
import com.sunseen.capacitormachine.databinding.FragmentEditParameterBinding;
import com.sunseen.capacitormachine.modules.parameter.productivetask.event.SetParameterEvent;
import com.sunseen.capacitormachine.modules.parameter.productivetask.event.SetSameIVEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.WeakHashMap;

import me.yokeyword.fragmentation.ISupportFragment;

/**
 * @author zest
 */
public class EditFragment extends BaseFragment {
    @Override
    protected int setLayout() {
        return R.layout.fragment_edit_parameter;
    }

    private final String batchId = "batchId";
    private final String status = "status";
    private final String deviceNo = "deviceNo";
    private final int parameterCount = 76;

    private WeakHashMap<String, Object> flowCardParameterMap = new WeakHashMap<>();
    private WeakHashMap<String, Object> processParameterMap = new WeakHashMap<>();
    private ISupportFragment[] fragments = null;

    private int curFragmentPos = 0;

    @Override
    protected void onBindView(ViewDataBinding viewDataBinding) {
        flowCardParameterMap.put(status, 0);//生产状态初始化为0
        flowCardParameterMap.put(deviceNo, "6812B066");//设备编号默认程序填写
        processParameterMap.put(deviceNo, "6812B066");
        processParameterMap.put("instrumentFrequency", 120);//仪表频率默认120Hz
        processParameterMap.put(status, 0);
        EventBus.getDefault().register(this);
        final EditFlowCardFragment fragment1 = new EditFlowCardFragment();
        final EditSortingParameterFragment fragment2 = new EditSortingParameterFragment();
        final EditPowerSupplyFragment fragment3 = new EditPowerSupplyFragment();
        final EditSprayCodeFragment fragment4 = new EditSprayCodeFragment();
        final EditAgingParameterFragment fragment5 = new EditAgingParameterFragment();
        fragments = new ISupportFragment[]{fragment1, fragment2, fragment3, fragment4, fragment5};

        FragmentEditParameterBinding binding = (FragmentEditParameterBinding) viewDataBinding;
        binding.toolBar.setOnClickListener((view) -> hideKeyBoardPop());
        binding.rgFormMenu.setOnCheckedChangeListener((RadioGroup group, int checkedId) -> {
            switch (checkedId) {
                case R.id.rb_product_flow: {
                    showHideFragment(fragments[0], fragments[curFragmentPos]);
                    curFragmentPos = 0;
                }
                break;
                case R.id.rb_sorting_parameter: {
                    showHideFragment(fragments[1], fragments[curFragmentPos]);
                    curFragmentPos = 1;
                }
                break;
                case R.id.rb_power_supply: {
                    showHideFragment(fragments[2], fragments[curFragmentPos]);
                    curFragmentPos = 2;
                }
                break;
                case R.id.rb_spray_code: {
                    showHideFragment(fragments[3], fragments[curFragmentPos]);
                    curFragmentPos = 3;
                }
                break;
                case R.id.rb_aging_process: {
                    showHideFragment(fragments[4], fragments[curFragmentPos]);
                    curFragmentPos = 4;
                }
                break;
                default:
                    Log.e("test", "rgFormMenu checkedId default");
                    break;
            }

        });
        binding.saveParameterBtn.setOnClickListener((View v) -> {
            if (flowCardParameterMap.containsKey(batchId)) {
                processParameterMap.put(status, 0);
                Log.e("test", "param count = " + processParameterMap.size());
                if (processParameterMap.size() == parameterCount) {
                    saveFlowCardParameter();
                    saveProcessParameter();
                } else {
                    Toast.makeText(getContext(), R.string.parameter_not_set_all, Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(getContext(), R.string.please_set_the_ids, Toast.LENGTH_SHORT).show();
            }
        });
        loadMultipleRootFragment(R.id.fragment_container, 0, fragments);
    }

    private boolean flowCardSave = false;
    private boolean processSave = false;

    private void checkSaveCount() {
        if (flowCardSave && processSave) {
            Toast.makeText(_mActivity, "参数保存成功", Toast.LENGTH_SHORT).show();
            pop();
        }
    }

    private void saveFlowCardParameter() {
        if (!flowCardSave) {
            RestClient.builder()

                    .url(HttpUtil.FlowCard)
                    .params(flowCardParameterMap)
                    .success((String response) -> {
                        JSONObject rootObj = JSON.parseObject(response);
                        if (rootObj.getIntValue(status) == 1) {
                            flowCardSave = true;
                            checkSaveCount();
                        } else {
                            String msg = rootObj.getString("message");
                            if (msg == null) {
                                msg = "未知错误信息";
                            }
                            Toast.makeText(_mActivity, "流转单保存失败: " + msg, Toast.LENGTH_SHORT).show();
                        }
                    })
                    .failure(() -> {
                        Log.e("test", "流转单保存失败");
                        Toast.makeText(_mActivity, "流转单保存失败", Toast.LENGTH_SHORT).show();
                    })
                    .error((int code, String msg) -> {
                        Log.e("test", "流转单保存错误: " + code + " " + msg);
                        Toast.makeText(_mActivity, "流转单保存错误: " + msg, Toast.LENGTH_SHORT).show();
                    })
                    .build()
                    .post();
        }
    }

    private void saveProcessParameter() {
        if (!processSave) {
            RestClient.builder()
                    .url(HttpUtil.Process)
                    .params(processParameterMap)
                    .success((String response) -> {
                        JSONObject rootObj = JSON.parseObject(response);
                        if (rootObj.getIntValue(status) == 1) {
                            processSave = true;
                            checkSaveCount();
                        } else {
                            String msg = rootObj.getString("message");
                            if (msg == null) {
                                msg = "未知错误信息";
                            }
                            Toast.makeText(_mActivity, "工艺参数保存失败: " + msg, Toast.LENGTH_SHORT).show();
                        }
                    })
                    .failure(() -> {
                        Log.e("test", "工艺参数保存失败");
                        Toast.makeText(_mActivity, "工艺参数保存失败", Toast.LENGTH_SHORT).show();
                    })
                    .error((int code, String msg) -> {
                        Log.e("test", "工艺参数保存错误: " + code + " " + msg);
                        Toast.makeText(_mActivity, "工艺参数保存错误: " + msg, Toast.LENGTH_SHORT).show();
                    })
                    .build()
                    .post();
        }
    }

    private void hideKeyBoardPop() {
        hideSoftInput();
        pop();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSetParamer(SetParameterEvent event) {
        if (event.isProcess()) {
            processParameterMap.put(event.getKey(), event.getValue());
        } else {
            Log.e("test", "key = " + event.getKey() + " content = " + event.getValue());
            flowCardParameterMap.put(event.getKey(), event.getValue());
            if (batchId.equals(event.getKey())) {
                processParameterMap.put(batchId, event.getValue());
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSetSameIv(SetSameIVEvent event) {
        if (event.isSameI()) {
            processParameterMap.put("I1", event.getValue());
            processParameterMap.put("I2", event.getValue());
            processParameterMap.put("I3", event.getValue());
            processParameterMap.put("I4", event.getValue());
            processParameterMap.put("I5", event.getValue());
            processParameterMap.put("I6", event.getValue());
            processParameterMap.put("I7", event.getValue());
            processParameterMap.put("I8", event.getValue());
            processParameterMap.put("I9", event.getValue());
            processParameterMap.put("I10", event.getValue());
            processParameterMap.put("I11", event.getValue());
            processParameterMap.put("I12", event.getValue());
            processParameterMap.put("I13", event.getValue());
            processParameterMap.put("I14", event.getValue());
            processParameterMap.put("I15", event.getValue());
            processParameterMap.put("I16", event.getValue());
            processParameterMap.put("I17", event.getValue());
            processParameterMap.put("I18", event.getValue());
            processParameterMap.put("chargeI", event.getValue());
            processParameterMap.put("surgeI", event.getValue());
            processParameterMap.put("testI", event.getValue());
        } else {
            processParameterMap.put("V1", event.getValue());
            processParameterMap.put("V2", event.getValue());
            processParameterMap.put("V3", event.getValue());
            processParameterMap.put("V4", event.getValue());
            processParameterMap.put("V5", event.getValue());
            processParameterMap.put("V6", event.getValue());
            processParameterMap.put("V7", event.getValue());
            processParameterMap.put("V8", event.getValue());
            processParameterMap.put("V9", event.getValue());
            processParameterMap.put("V10", event.getValue());
            processParameterMap.put("V11", event.getValue());
            processParameterMap.put("V12", event.getValue());
            processParameterMap.put("V13", event.getValue());
            processParameterMap.put("V14", event.getValue());
            processParameterMap.put("V15", event.getValue());
            processParameterMap.put("V16", event.getValue());
            processParameterMap.put("V17", event.getValue());
            processParameterMap.put("V18", event.getValue());
            processParameterMap.put("chargeV", event.getValue());
            processParameterMap.put("surgeV", event.getValue());
            processParameterMap.put("testV", event.getValue());
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }
}
